<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件上传测试</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            margin: 20px;
            background-color: #f5f7fa;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        .form-group input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            margin-right: 10px;
        }
        
        .btn-primary {
            background: #007bff;
            color: white;
        }
        
        .btn-success {
            background: #28a745;
            color: white;
        }
        
        .result {
            margin-top: 20px;
            padding: 15px;
            border-radius: 4px;
            border-left: 4px solid #007bff;
            background: #f8f9fa;
        }
        
        .error {
            border-left-color: #dc3545;
            background: #f8d7da;
            color: #721c24;
        }
        
        .success {
            border-left-color: #28a745;
            background: #d4edda;
            color: #155724;
        }
        
        .progress-bar {
            width: 100%;
            height: 20px;
            background-color: #f0f0f0;
            border-radius: 10px;
            overflow: hidden;
            margin: 10px 0;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #007bff, #0056b3);
            width: 0%;
            transition: width 0.3s ease;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔧 文件上传功能测试</h1>
        
        <!-- 登录区域 -->
        <div class="form-group">
            <h3>1. 登录测试</h3>
            <label for="username">用户名:</label>
            <input type="text" id="username" value="sbxnh">
            <label for="password">密码:</label>
            <input type="password" id="password" value="123456">
            <button class="btn btn-primary" onclick="login()">登录</button>
            <div id="loginResult"></div>
        </div>
        
        <!-- 文件上传区域 -->
        <div class="form-group">
            <h3>2. 文件上传测试</h3>
            <label for="testFile">选择文件:</label>
            <input type="file" id="testFile" accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt">
            <button class="btn btn-success" onclick="uploadFile()">上传文件</button>
            <div id="uploadProgress" style="display: none;">
                <div class="progress-bar">
                    <div class="progress-fill"></div>
                </div>
                <span class="progress-text">上传中...</span>
            </div>
            <div id="uploadResult"></div>
        </div>
        
        <!-- 文件预览区域 -->
        <div class="form-group">
            <h3>3. 文件预览测试</h3>
            <input type="text" id="previewUrl" placeholder="输入文件URL进行预览">
            <button class="btn btn-primary" onclick="previewFile()">预览文件</button>
            <div id="previewResult"></div>
        </div>
    </div>

    <script>
        const API_BASE = 'http://localhost:8080';
        let token = '';

        // 登录功能
        async function login() {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const resultDiv = document.getElementById('loginResult');

            try {
                const response = await fetch(`${API_BASE}/auth/login`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ username, password })
                });

                if (response.ok) {
                    const data = await response.json();
                    token = data.token;
                    localStorage.setItem('token', token);
                    resultDiv.innerHTML = '<div class="result success">✅ 登录成功！Token已保存</div>';
                } else {
                    const errorText = await response.text();
                    resultDiv.innerHTML = `<div class="result error">❌ 登录失败: ${errorText}</div>`;
                }
            } catch (error) {
                resultDiv.innerHTML = `<div class="result error">❌ 网络错误: ${error.message}</div>`;
            }
        }

        // 文件上传功能
        async function uploadFile() {
            const fileInput = document.getElementById('testFile');
            const file = fileInput.files[0];
            const resultDiv = document.getElementById('uploadResult');
            const progressDiv = document.getElementById('uploadProgress');
            const progressFill = progressDiv.querySelector('.progress-fill');

            if (!file) {
                resultDiv.innerHTML = '<div class="result error">❌ 请先选择文件</div>';
                return;
            }

            if (!token) {
                token = localStorage.getItem('token');
                if (!token) {
                    resultDiv.innerHTML = '<div class="result error">❌ 请先登录</div>';
                    return;
                }
            }

            const formData = new FormData();
            formData.append('file', file);
            formData.append('category', 'publication');

            try {
                progressDiv.style.display = 'block';
                progressFill.style.width = '0%';

                // 模拟进度
                let progress = 0;
                const progressInterval = setInterval(() => {
                    progress += 10;
                    progressFill.style.width = progress + '%';
                    if (progress >= 90) {
                        clearInterval(progressInterval);
                    }
                }, 100);

                const response = await fetch(`${API_BASE}/files/upload`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    },
                    body: formData
                });

                clearInterval(progressInterval);
                progressFill.style.width = '100%';

                if (response.ok) {
                    const result = await response.json();
                    resultDiv.innerHTML = `
                        <div class="result success">
                            ✅ 文件上传成功！<br>
                            文件名: ${result.fileName}<br>
                            文件大小: ${(result.fileSize / 1024).toFixed(2)} KB<br>
                            访问URL: ${result.fileUrl}<br>
                            <button class="btn btn-primary" onclick="document.getElementById('previewUrl').value='${result.fileUrl}'">设置预览URL</button>
                        </div>
                    `;
                } else {
                    const errorText = await response.text();
                    resultDiv.innerHTML = `<div class="result error">❌ 上传失败: ${errorText}</div>`;
                }

                setTimeout(() => {
                    progressDiv.style.display = 'none';
                }, 2000);

            } catch (error) {
                progressDiv.style.display = 'none';
                resultDiv.innerHTML = `<div class="result error">❌ 上传错误: ${error.message}</div>`;
            }
        }

        // 文件预览功能
        function previewFile() {
            const url = document.getElementById('previewUrl').value;
            const resultDiv = document.getElementById('previewResult');

            if (!url) {
                resultDiv.innerHTML = '<div class="result error">❌ 请输入预览URL</div>';
                return;
            }

            const fullUrl = url.startsWith('http') ? url : `${API_BASE}${url}`;
            
            resultDiv.innerHTML = `
                <div class="result success">
                    📄 文件预览:<br>
                    <iframe src="${fullUrl}" style="width: 100%; height: 400px; border: 1px solid #ddd; margin-top: 10px;"></iframe>
                    <br>
                    <a href="${fullUrl.replace('/preview/', '/download/')}" target="_blank">📥 下载文件</a>
                </div>
            `;
        }

        // 页面加载时检查登录状态
        window.onload = function() {
            const savedToken = localStorage.getItem('token');
            if (savedToken) {
                token = savedToken;
                document.getElementById('loginResult').innerHTML = '<div class="result success">✅ 已有保存的登录状态</div>';
            }
        };
    </script>
</body>
</html>
